package uutalk.netcloud.talk.app.ui.Activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.makeramen.roundedimageview.RoundedImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.android.BaseActivity;
import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.ZxingUtils;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;
import uutalk.netcloud.talk.base.util.thirdpart.ImageLoader;
import uutalk.netcloud.talk.base.util.thirdpart.QiNiuManager;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.base.widget.CenterEditTips;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.JoinActAuthBean;
import uutalk.netcloud.talk.model.bean.SimpleEventType;

/**
 * Created by pmt
 */

public class ActShareActivity extends BaseActivity {

    private final static String TAG = "ActShareActivity";

    @BindView(R.id.qr_code)
    ImageView qr_code;

    @BindView(R.id.act_name)
    TextView act_name;

    @BindView(R.id.share_tools)
    GridView share_tools;

    @BindView(R.id.user_icon)
    RoundedImageView userIcon;


    Bitmap bitmap= null;
    @Override
    public int layoutId() {
        return R.layout.activity_share;
    }

    @Override
    public boolean autoBindEvent() {
        return true;
    }

    @Override
    public void init() {
        Intent intent=getIntent();
        if(intent !=null)
        {
            ImageLoader.loadImage(mActivity,
                    QiNiuManager.QINIU_HOST + UserManager.getInstance().getUserInfo().getPicture(),
                    userIcon);

            String groupName = intent.getStringExtra("group_name");
            String groupId = intent.getStringExtra("group_id");
            act_name.setText(groupName);
            initToolData();

            bitmap = ZxingUtils.encodeAsBitmap("HD" + groupId);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            qr_code.setImageBitmap(bitmap);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttMessageEvent(MqttMessageEvent event) {
        if(CMDConstant.JOIN_GROUP_AUTH_CMD.equals(event.getMessage().getCmd()))
        {
            //你是群主，接收到了申请,点击确定之后回复对方
            Log.d("talk", "你是群主，接收到了申请");
            EventMamager.getInstance().postEvent(SimpleEventType.GROUP_AUTH_FINISH);
            final JoinActAuthBean joinActAuthBean = JSON.parseObject(event.getMessage().toString(), JoinActAuthBean.class);
            final CenterEditTips alertView = new CenterEditTips(mActivity);
            alertView.setTitleStr("申请认证");
            alertView.setEditIDVisible(View.VISIBLE);
            //alertView.setsureButtonStr(getResources().LanguageUtil.getStringById(R.string.m02_chat_msg_btn_sure));
            alertView.setType(CenterEditTips.TYPE_DOUBLE);
            alertView.setEditIDStr(joinActAuthBean.getAuth_msg());
            alertView.setClickListener(new CenterEditTips.OnClickListener() {

                @Override
                public void onSureClick()
                {
                    EventMamager.getInstance().postEvent(SimpleEventType.GROUP_AUTH_FINISH);
                    if (MQTTManager.getInstance().isConnected()) {
                        String strReq = alertView.getEditIDStr();
                        String strRsp = alertView.getEditTextString();
                        Publication publication = PublishFactory.createPublication(BussinessBeanFactory
                                .createJoinGroupAuthRspBean(joinActAuthBean.getGroup_id(),joinActAuthBean.getGroup_name(),
                                        joinActAuthBean.getUser_id(),
                                        joinActAuthBean.getOwner_id(),
                                        joinActAuthBean.getAuth_msg(),"0",strRsp));
                        Log.d(TAG, publication.getPayload());
                        MQTTManager.getInstance().publish(publication);
                        Log.d("talk", "groupID:" + strReq + " strGroupName:" + strRsp);
                    } else {
                        ToastUtil.makeToast("网络链接异常");
                    }
                }

                @Override
                public void onCancelClick()
                {
                    EventMamager.getInstance().postEvent(SimpleEventType.GROUP_AUTH_FINISH);
                    if (MQTTManager.getInstance().isConnected()) {
                        String strRsp = alertView.getEditTextString();
                        Publication publication = PublishFactory.createPublication(BussinessBeanFactory
                                .createJoinGroupAuthRspBean(joinActAuthBean.getGroup_id(),joinActAuthBean.getGroup_name(),
                                        joinActAuthBean.getUser_id(),
                                        joinActAuthBean.getOwner_id(),
                                        joinActAuthBean.getAuth_msg(),"1",strRsp));
                        Log.d(TAG, publication.getPayload());
                        MQTTManager.getInstance().publish(publication);
                    } else {
                        ToastUtil.makeToast("网络链接异常");
                    }
                }
            });
            alertView.show();
        }
    }

    @OnClick(R.id.act_share)
    public void onClickShare()
    {
        File f= null;
        if(bitmap != null){
            f = saveImage(bitmap);
        }
        else
        {
            return;
        }
        Intent intent=new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");

        Uri u = Uri.fromFile(f);
        intent.putExtra(Intent.EXTRA_STREAM, u);

        intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
        intent.putExtra(Intent.EXTRA_TEXT, "分享成功");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(Intent.createChooser(intent, "UU对讲"));
    }


    void initToolData()
    {
        ArrayList<ToolBean> toolList = new ArrayList<ToolBean>();
        ToolBean toolBean = new ToolBean();
        toolBean.toolID  = 1000;
        toolBean.toolName = "微博";
        toolBean.resID    = R.drawable.icon_share_weibo;
        toolList.add(toolBean);

        toolBean = new ToolBean();
        toolBean.toolID  = 1001;
        toolBean.toolName = "微信";
        toolBean.resID    = R.drawable.icon_share_wetchat;
        toolList.add(toolBean);

        toolBean = new ToolBean();
        toolBean.toolID  = 1002;
        toolBean.toolName = "QQ";
        toolBean.resID    = R.drawable.icon_share_qq;
        toolList.add(toolBean);

        toolBean = new ToolBean();
        toolBean.toolID  = 1003;
        toolBean.toolName = "朋友圈";
        toolBean.resID    = R.drawable.icon_share_friend;
        toolList.add(toolBean);

        ToolAdapter toolAdapter = new ToolAdapter(mActivity, toolList);
        share_tools.setAdapter(toolAdapter);

        share_tools.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                File f= null;
                if(bitmap != null){
                    f = saveImage(bitmap);
                }
                else
                {
                    return;
                }
                Intent intent=new Intent(Intent.ACTION_SEND);
                intent.setType("image/*");

                Uri u = Uri.fromFile(f);
                intent.putExtra(Intent.EXTRA_STREAM, u);

                intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                intent.putExtra(Intent.EXTRA_TEXT, "分享成功");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(Intent.createChooser(intent, "UU对讲"));
            }
        });
    }

    public File saveImage(Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "UUTalk");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "群组二维码" + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    class ToolBean{
        int toolID;
        String toolName;//工具名称
        int    resID;//图像id
    }

    class ToolAdapter extends BaseAdapter{

        ArrayList<ToolBean> toolList = null;
        Context mContext;
        public ToolAdapter(Context mContext, ArrayList<ToolBean> toolList){
            this.toolList = toolList;
            this.mContext = mContext;
        }
        @Override
        public int getCount() {
            return toolList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int pos, View convertView, ViewGroup viewGroup) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_grid_share, null);
                holder = new ViewHolder();
                holder.titleTextView = (TextView) convertView.findViewById(R.id.name);
                holder.iconImageView = (ImageView) convertView.findViewById(R.id.icon);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.titleTextView.setText(toolList.get(pos).toolName);
            holder.iconImageView.setImageDrawable(
                    getResources().getDrawable(toolList.get(pos).resID));
            return convertView;
        }


    }

    static class ViewHolder {
        TextView titleTextView;
        ImageView iconImageView;
    }

}
